import { useState, useEffect, useRef } from 'react';

const formatTime = (seconds) => {
    if (seconds <= 0) return '00:00:00';
    
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const remainingSeconds = seconds % 60;

    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
};

const useCountdown = (initialTimeout, onTimeUp) => {
    const [timeLeft, setTimeLeft] = useState(initialTimeout || 0);
    const [isExpired, setIsExpired] = useState(false);
    const onTimeUpRef = useRef(onTimeUp);

    useEffect(() => {
        onTimeUpRef.current = onTimeUp;
    }, [onTimeUp]);

    useEffect(() => {
        if (!initialTimeout || initialTimeout <= 0) {
            setIsExpired(true);
            setTimeLeft(0);
            return;
        }

        setTimeLeft(initialTimeout);
        setIsExpired(false);

        const timer = setInterval(() => {
            setTimeLeft(prev => {
                if (prev <= 1) {
                    setIsExpired(true);
                    onTimeUpRef.current && onTimeUpRef.current();
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);

        return () => clearInterval(timer);
    }, [initialTimeout]); 

    return [formatTime(timeLeft), isExpired];
};

export default useCountdown;
